import cn.com.callback.ServiceBackInvoke
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.jdbc.core.JdbcTemplate;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import java.time.Instant;

/**
 *
 * @Title: aipHSTchatRequestUp
 * @Description:华盛证券 将brand 伪json 处理更新到其新增的字段上 --外部接口
 * @author: chieh
 * @date 2022-12-16 10:28:00
 *
 */

public class aipHSTchatRequestUp implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTchatRequestUp.class);
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime ;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            String id="";
            String brand="";

            //查询 brand
            //List selectbrandList = eliteBean.chaxun_sql("select id,brand from chat_request where 1=1 and creation_time>=Unix_Timestamp(TIMESTAMP(CURDATE()))*1000 and creation_time<=Unix_Timestamp(TIMESTAMP(DATE_SUB(curdate(),INTERVAL -1 DAY)))*1000 and channel is null and link is  null and LENGTH(brand)>3 and brand is not null", "dataSource");
            
			//List selectbrandList = eliteBean.chaxun_sql("select id,brand from chat_request where 1=1 and creation_time>=Unix_Timestamp(TIMESTAMP(DATE_SUB(curdate(),INTERVAL +2 DAY)))*1000  and channel is null and link is  null and LENGTH(brand)>3 and brand is not null", "dataSource");
            List selectbrandList = eliteBean.chaxun_sql("select id,brand from chat_request where 1=1 and creation_time>=Unix_Timestamp(TIMESTAMP(DATE_SUB(curdate(),INTERVAL +2 DAY)))*1000 and channel is null and link is  null and LENGTH(brand)>3 and brand is not null and brand!='WhatsApp'", "dataSource");
            def brandcount = selectbrandList.size();
            log.debug("待处理的数量 brandcount：" + brandcount);
            //判断如待处理的数据数量大于0则执行
            if(brandcount> 0){
                for(int i = 0; i<brandcount; i++) {
                    Map selectbrandMap = selectbrandList.get(i);
                    id = selectbrandMap.get("id");//唯一id
                    brand = selectbrandMap.get("brand");//brand数据
                    log.debug("id:" + id+"	brand:" + brand);

                    //增加异常机制，处置解析不合规的数据则跳出
                    try {
                        String link = "";
                        String channel = "";
                        if (brand != null && brand != "") {
                            brand = brand.replaceAll("“", "\"");
                            log.debug(brand);
                            JSONObject jsonObject = JSONObject.parseObject(brand);
                            link = jsonObject.get("link");
                            channel = jsonObject.get("channel");
                            log.debug("link:" + link + "	channel:" + channel);

                            //为null处理
                            if(link==null){
                                link="";
                            }
                            if(channel==null){
                                channel="";
                            }

                            //更新 channel link
                            def dataresult = eliteBean.update("update chat_request set channel='" + channel + "',link='" + link + "' where id='" + id + "'", "dataSource");
                            log.debug("dataresult:" + dataresult);
                        } else {
                            log.debug("无效数据跳过！");
                        }
                    }catch (Exception e) {
                        log.error("跳出下一次,解析异常:" + e.getMessage());
                        continue;
                    }

                }
            }

            //查询 网聊chat_request   表的   request_status_id 字段记录 是7  为客户放弃。
            // 但是实际这通会话接入人工了 且发送了有效对话   -- 赵杰 don  需要在客户点取消排队的时候判断会话是否生成
            // * request_status_id 字段记录 是4  是 异常掉线
            List selectycchatList = eliteBean.chaxun_sql("select cr.chat_session_id as chat_session_id,cr.id as chatid from chat_request cr  left join  chat_message cm on cr.chat_session_id=cm.chat_session_id \n" +
                    "   where  post_time>creation_time and length(chat_user_id)=6 and chat_user_id not like 'BOT%' \n" +
                    " and (cr.request_status_id=4 or cr.request_status_id=7)    and cr.to_chat_user_id is not null\n" +
                    "                                   GROUP BY cr.chat_session_id,cr.id \n" +
                    "                                   ORDER BY 1 desc limit 1000", "dataSource");
            def ycchatcount = selectycchatList.size();
            log.debug("待处理的数量 ycchatcount：" + ycchatcount);
            //判断如待处理的数据数量大于0则执行
            String chatid="";
            String chat_session_id="";
            int xfcount=0;

            if(ycchatcount> 0){
                for(int i = 0; i<ycchatcount; i++) {
                    Map selectycchatMap = selectycchatList.get(i);
                    chatid = selectycchatMap.get("chatid");
                    chat_session_id = selectycchatMap.get("chat_session_id");
                    log.debug("chatid:" + chatid+"	chat_session_id:" + chat_session_id);

                    String UpSql = "update chat_request set request_status_id=1 where id='" + chatid + "'  and chat_session_id='" + chat_session_id+"'";
                    def countresult= eliteBean.update(UpSql, "dataSource")
                    xfcount=xfcount+countresult;

                }
                log.debug("网聊chat_request表的request_status_id涉及修复条数：" + xfcount);

            }
			
			//处理 chat_message 消息内图片url携带 &thumb=true 问题导致前端看不到
            def updateurlresult = eliteBean.update("update chat_message set message_text=REPLACE(message_text,'&thumb=true','') where 1=1 and post_time>=Unix_Timestamp(TIMESTAMP(CURDATE()))*1000 and post_time<Unix_Timestamp(TIMESTAMP(DATE_SUB(curdate(),INTERVAL -1 DAY)))*1000   and message_text like '%&thumb=true%'", "dataSource");
            log.debug("updateurlresult:" + updateurlresult);


            // 查询 网聊chat_request   表的   request_status_id 字段记录 是1  为进线成功
            // 但是实际这通会话转人工失败了  to_chat_user_id 为空
            List selectuseridisnull =eliteBean.chaxun_sql("select id from chat_request cr where cr.request_type_id=4 and to_chat_user_id is null and cr.request_status_id=1","dataSource");

            def idcount = selectuseridisnull.size();
            log.debug("待处理的数量 idcount：" + idcount);

            xfcount=0;
            if(idcount>0){
                for (int i = 0; i <idcount ; i++) {
                    Map selectuseridisnullMap = selectuseridisnull.get(i);
                    def request_id = selectuseridisnullMap.get("id");
                    log.debug("request_id:" + request_id);

                    String t="update chat_request set request_status_id=7 where id="+request_id;
                    def updateid=eliteBean.update(t,"dataSource");
                    xfcount=xfcount+updateid;

                }
                log.debug("网聊chat_request表的request_status_id涉及修复条数：" + xfcount);
            }

            //查询 chat_message 表里首次响应数重复的数据
            xfcount=0;
            List messagecf =eliteBean.chaxun_sql("select sum(first_reply) as fr,chat_session_id  from chat_message  \n" +
                    "where post_time<Unix_Timestamp(TIMESTAMP(DATE_SUB(curdate(),INTERVAL -1 DAY)))*1000 GROUP BY chat_session_id having fr>1 ORDER BY id desc","dataSource");
            log.info("messagecf："+messagecf.size());

            if(messagecf.size()>0){
                for (int i = 0; i < messagecf.size(); i++) {
                    Map messagecfMap = messagecf.get(i);
                    def session_id = messagecfMap.get("chat_session_id");
                    log.info("chat_message 表里首次响应数重复的数据session_id:" + session_id);

                    List messagecfid =eliteBean.chaxun_sql(" select chat_session_id,max(id) as id from chat_message \n" +
                            "  where post_time<Unix_Timestamp(TIMESTAMP(DATE_SUB(curdate(),INTERVAL -1 DAY)))*1000   and first_reply=1 and chat_session_id="+session_id,"dataSource");

                    for (int u = 0; u < messagecfid.size(); u++) {
                        Map messagecfidMap = messagecfid.get(u);
                        def cfid = messagecfidMap.get("id");
                        log.info("拿到最后一次的首次响应id:" + cfid);
                        xfcount=eliteBean.update("update chat_message set first_reply=0 where first_reply=1 and id!="+cfid+" and chat_session_id="+session_id,"dataSource");

                    }
                }
                log.debug("网聊chat_message表的首次响应数涉及修复条数：" + xfcount);
            }

            outData = "{\"resultcode\":\"1\",\"resultmessage\":\"处理成功\"}";
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        log.debug("更新chat_request表 信息完成返回结果:" + outData);

        return outData;
    }

}
